package com.tom.demo.service.system.impl;

import cn.hutool.core.lang.Snowflake;
import com.tom.demo.common.entity.SysDept;
import com.tom.demo.common.response.Result;
import com.tom.demo.common.utils.SecurityUtils;
import com.tom.demo.dto.DeptDto;
import com.tom.demo.mapper.SysDeptMapper;
import com.tom.demo.service.system.DeptService;
import com.tom.demo.vo.Deprecates;
import com.tom.demo.vo.DeptEchartsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Slf4j
@Service
public class DeptServiceImpl implements DeptService {

    @Resource
    private SysDeptMapper sysDeptMapper;

    @Resource
    private Snowflake snowflake;

    @Override
    public List<SysDept> getDepartment() {
        //获取当前登录的用户id
        List<SysDept> sysDepots;
        String userId = SecurityUtils.getLoginUserId();
        if(SecurityUtils.isAdmin(userId)){
            sysDepots = sysDeptMapper.findByAll();
        }else {
            String deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
            //postgresql的递归向上查询，mysql8.0后的版本也支持这种方式
            sysDepots = sysDeptMapper.findByUserIdUp(deptId);
        }
        return sysDepots;
    }

    @Override
    public Result insertDepartment(DeptDto deptDto) {
        SysDept dept = sysDeptMapper.findByDeptCode(deptDto.getDeptCode());
        if(dept != null){
            return Result.error("部门编码已经存在，不能重复添加");
        }
        SysDept sysDept = new SysDept();
        BeanUtils.copyProperties(deptDto,sysDept);
        sysDept.setDeptId(snowflake.nextIdStr());
        String userName = SecurityUtils.getLoginUserName();
        sysDept.setCreateBy(userName);
        int insert = sysDeptMapper.insert(sysDept);
        return insert > 0 ? Result.success() : Result.error("新增部门失败");
    }

}
